#!/usr/bin/python
'''
Created on 2013-6-19
find class from jars
@author: zhc
'''

from zipfile import BadZipfile
import sys
import os
import zipfile

# get input jar name and input directories
findjar = sys.argv[1]
jardirs = []
for i in range(2, len(sys.argv)):
    if not os.path.isdir(sys.argv[i]):
        print sys.argv[i], 'is not a directory!'
        sys.exit()
    else:
        jardirs.append(sys.argv[i])

# get all dir recursive
alljardirs = []
for jardir in jardirs:           
    for rootdir, subdirs,curfiles in os.walk(jardir):
        print rootdir
        alljardirs.append(rootdir)

# get all jar file into jarfiles
jarfiles = []
for jardir in alljardirs:
    dirfiles = os.listdir(jardir)
    for dirfile in dirfiles:
        print os.path.abspath(jardir) + os.sep + dirfile
        if os.path.isfile(os.path.abspath(jardir) + os.sep +dirfile) and dirfile.endswith('.jar'):
            jarfiles.append(os.path.abspath(jardir) + os.sep + dirfile)

# unzip jar file and find the jar and class
findedjars = []
for jar in jarfiles:
    try:
        zfile = zipfile.ZipFile(jar, 'r')
    except BadZipfile, e:
        print jar, e
        
    for f in zfile.namelist():
        if f.endswith('.class') and f.find(findjar)>-1:
            findedjars.append(f + ' @ ' + jar + ';    ')

# sys.stdout = open('log.txt', 'w')
print "=============result============="
for info in findedjars:
    print info
# print 'INFO: result has been redirected to findclassfromjars.log'


